<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店编号">
              <a-input placeholder="请输入名称模糊查询" v-model="queryParam.terminalCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店名称">
              <a-input placeholder="请输入名称模糊查询" v-model="queryParam.terminalName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="经销商名称">
              <a-input placeholder="请输入经销商名称" v-model="queryParam.custName"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item
              label="渠道类型">
              <a-select default-value=""
                        v-decorator="[ 'termChannel', {}]"
                        placeholder="请选择状态" v-model="queryParam.termChannel"
                        :getPopupContainer = "(target) => target.parentNode">
                <a-select-option value="NKA">NKA</a-select-option>
                <a-select-option value="RKA">RKA</a-select-option>
                <a-select-option value="LKA">LKA</a-select-option>
                <a-select-option value="NBBS">NBBS</a-select-option>
                <a-select-option value="RMBS">RMBS</a-select-option>
                <a-select-option value="MBS">MBS</a-select-option>
                <a-select-option value="Others">Others</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <template v-if="toggleSearchStatus">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店类型">
<!--              <cn-dict-select-tag placeholder="请选择门店类型" dict-code="terminal_type" triggerChange v-model="queryParam.terminalType"/>-->
              <cn-dict-select-tag placeholder="请选择门店类型" dict-code="terminal_type"  v-model="queryParam.terminalType"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="组织">
              <j-tree-select placeholder="请选择所属组织" v-model="queryParam.orgCode" v-decorator="['orgCode', {}]" data-type="org" />
            </a-form-item>
          </a-col>

                    </template>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
<!--      <a-button @click="handleEnable" type="primary">启用</a-button>-->
<!--      <a-button @click="handleDisable" type="primary">停用</a-button>-->
<!--      <a-button @click="handleTerminal" type="primary">关联终端</a-button>-->

<!--      <a-button type="primary" icon="download" @click="handleExportXls('单表示例')">导出</a-button>-->
<!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
<!--        <a-button type="primary" icon="import">导入</a-button>-->
<!--      </a-upload>-->
      <!-- 高级查询区域 -->
<!--      <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
<!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
<!--        <a-menu slot="overlay">-->
<!--          <a-menu-item key="1" @click="batchDel">-->
<!--            <a-icon type="delete"/>-->
<!--            删除-->
<!--          </a-menu-item>-->
<!--        </a-menu>-->
<!--        <a-button style="margin-left: 8px"> 批量操作-->
<!--          <a-icon type="down"/>-->
<!--        </a-button>-->
<!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{-->
<!--          selectedRowKeys.length }}</a>项-->
<!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--        <span style="float:right;">-->
<!--          <a @click="loadData()"><a-icon type="sync" />刷新</a>-->
<!--          <a-divider type="vertical" />-->
<!--          <a-popover title="自定义列" trigger="click" placement="leftBottom">-->
<!--            <template slot="content">-->
<!--              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">-->
<!--                <a-row>-->
<!--                  <template v-for="(item,index) in defColumns">-->
<!--                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">-->
<!--                        <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>-->
<!--                    </template>-->
<!--                  </template>-->
<!--                </a-row>-->
<!--              </a-checkbox-group>-->
<!--            </template>-->
<!--            <a><a-icon type="setting" />设置</a>-->
<!--          </a-popover>-->
<!--        </span>-->
<!--      </div>-->

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <div slot="filterDropdown">
          <a-card>
            <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
              <a-row>
                <template v-for="(item,index) in defColumns">
                  <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                    <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                  </template>
                </template>
              </a-row>
            </a-checkbox-group>
          </a-card>
        </div>
        <a-icon slot="filterIcon" type='setting' :style="{ fontSize:'16px',color:  '#108ee9' }" />

        <template slot="avatar" slot-scope="text, record, index">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="record.avatar" icon="user"/>
          </div>
        </template>
        <div slot="isActiveStatus" slot-scope="text,recode">
          {{text|isActiveStatus}}
        </div>
        <div slot="filterTerminalType" slot-scope="text,recode">
          {{text|filterTerminalType}}
        </div>
        <span slot="action" slot-scope="text, record">
          <a @click="handleWhite(record)">门店配置</a>
          <a-divider type="vertical"/>
          <a-dropdown>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
<!--    <stock-modal ref="stockModalForm" @ok="modalFormOk"></stock-modal>-->
    <terminal-modal ref="modalForm" @ok="modalFormOk"></terminal-modal>
    <WhiteModalCust
            modal-width="90%"
            ref="WhiteModalCust"
            @ok="handelSaveWhite" >
    </WhiteModalCust>
  </a-card>
</template>

<script>
  import WhiteModalCust from "./modules/WhiteModalCust";
  import {postAction} from '../../../api/manage';
  import terminalModal from '../customer-center/modules/CustListModal'
  import stockModal from './modules/stockModal'
  import JSuperQuery from '@/components/cn-form/JSuperQuery.vue';
  import JInput from '@/components/cn-form/JInput.vue';
  import {initDictOptions, filterDictText,filterDictTextByCache} from '@/components/dict/CnDictSelectUtil'
  import { PageListMixin } from '@/mixins/PageListMixin'
  import Vue from 'vue'
  import { filterObj } from '@/utils/util';
  import JTreeSelect from '@/components/cn-form/JTreeSelect'
  //高级查询modal需要参数
  const superQueryFieldList=[
    {
      type: "string",
      value: "name",
      text: "用户名"
    }, {
      type: "int",
      value: "age",
      text: "年龄"
    }, {
      type: "date",
      value: "birthday",
      text: "生日"
    }
  ]
  export default {
    name: "terminal-cust-list",
    mixins:[PageListMixin],
    components: {
      terminalModal,
      stockModal,
      JSuperQuery,
      JInput,
      JTreeSelect,
      WhiteModalCust
    },
    data() {
      return {
        description: '单表示例列表',
        //字典数组缓存
        sexDictOptions: [],
        importExcelUrl:`${window._CONFIG['domianURL']}/test/cn-formDemo/importExcel`,
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        //列定义
        defColumns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },

          {
            title: '门店头像',
            align: 'center',
            dataIndex: 'avatar',
            width: 80,
            ellipsis: true,
            scopedSlots: {customRender: 'avatar'},
          },
          {
            title: '门店编号',
            align: "center",
            dataIndex: 'terminalCode'
          },
          {
            title: '门店名称',
            align: "center",
            dataIndex: 'terminalName'
          },
          {
            title: '渠道类型',
            align: "center",
            dataIndex: 'termChannel'
          },
          {
            title: '门店类型',
            align: "center",
            dataIndex: 'terminalType'
          },
          {
            title: '门店等级',
            align: "center",
            dataIndex: 'terminalLevel'
          },
          {
            title: '所属组织',
            align: "center",
            dataIndex: 'orgName'
          },
          {
            title: '经销商名称',
            align: "center",
            dataIndex: 'custName'
          },
          {
            title: '负责人',
            align: "center",
            dataIndex: 'linkman'
          },
          {
            title: '营业执照',
            align: "center",
            dataIndex: 'businessLicense'
          },
          {
            title: '联系电话',
            align: "center",
            dataIndex: 'telephone'
          },
          {
            title: '状态',
            align: "center",
            dataIndex: 'status',
            scopedSlots:{customRender:'isActiveStatus'}
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'},
          }
        ],
        url: {
          list: window._CONFIG['domianURL'] + "/cnTerminalController/custFindTerminalListNew",
          delete: window._CONFIG['domianURL'] + "/cnTerminalController/deleteByid",
          detail:window._CONFIG['domianURL'] + '/cnTerminalController/getCnTerminalByIdOrTerminalCode',

          deleteBatch: "/test/cn-formDemo/deleteBatch",
          exportXlsUrl: "/test/cn-formDemo/exportXls",
          deleteTag:window._CONFIG['domianURL'] + '/cnTerminalController/deleteLabels',
          saveOrUpdateTag:window._CONFIG['domianURL'] + '/cnTerminalController/saveOrUpdateLabels'
        },
        fieldList:superQueryFieldList,
        currentWhite:{}
      }
    },
    methods: {
      async handleWhite(record){
        this.currentWhite = record
        this.$refs.WhiteModalCust.showModal(record.terminalCode)
      },
      handelSaveWhite(typeList,productList,positionList,record){
        let that = this
        const tList = typeList.map(type=>Object.assign({
          code:type.code,
          name:type.name,
          dataType:3
        }))
        const pList = productList.map(type=>Object.assign({
          code:type.code,
          name:type.name,
          remarks:type.imgUrl,
          dataType:4
        }))
        const positions = positionList.map(type=>Object.assign({
          code:type.positionCode,
          name:type.positionName,
          dataType:5
        }))
        if(!record.extendVos) record.extendVos = []
        const retainRows = record.extendVos.filter(row=>[1,2].includes(Number(row.dataType)))
        record.extendVos = [...retainRows,...tList,...pList,...positions]
        that.loadData();
        postAction(window._CONFIG['domianURL'] + "/cnTerminalController/saveTerExtendNew", record).then(async (res) => {
          if (res.success) {
            that.$message.success(res.message);
            this.$refs.WhiteModalCust.showModal('')
            this.$refs.WhiteModalCust.close()
          } else {
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.$refs.WhiteModalCust.confirmLoading = false;
          //that.close();
        })
      },
      async handleStock(record){
        const modal = this.$refs.stockModalForm
        modal.edit(record);
        modal.title = "详情";
        modal.disableSubmit = true;
        return true
      },
      postAction,
      getQueryParams(){
        //高级查询器
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);

        param.field = this.getQueryField();
        param.current = this.ipagination.current;
        param.size = this.ipagination.pageSize;
        delete param.birthdayRange; //范围参数不传递后台
        return filterObj(param);
      },
      initDictConfig() {
        console.log("--我才是真的方法!--")
        //初始化字典 - 性别
        initDictOptions('sex').then((res) => {
          if (res.success) {
            this.sexDictOptions = res.result;
          }
        });
      },
      //跳转单据页面
      jump() {
        this.$notification.success('跳转 ： jump')
      },
      onBirthdayChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.birthday_begin=dateString[0];
        this.queryParam.birthday_end=dateString[1];
      },
      //列设置更改事件
      onColSettingsChange (checkedValues) {
        var key = this.$route.name+":colsettings";
        Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
        this.settingColumns = checkedValues;
        const cols = this.defColumns.filter(item => {
          if(item.key =='rowIndex'|| item.dataIndex=='action'){
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns =  cols;
      },
      initColumns(){
        //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

        var key = this.$route.name+":colsettings";
        let colSettings= Vue.ls.get(key);
        if(colSettings==null||colSettings==undefined){
          let allSettingColumns = [];
          this.defColumns.forEach(function (item,i,array ) {
            allSettingColumns.push(item.dataIndex);
          })
          this.settingColumns = allSettingColumns;
          this.columns = this.defColumns;
        }else{
          this.settingColumns = colSettings;
          const cols = this.defColumns.filter(item => {
            if(item.key =='rowIndex'|| item.dataIndex=='action'){
              return true;
            }
            if (colSettings.includes(item.dataIndex)) {
              return true;
            }
            return false;
          })
          this.columns =  cols;
        }
      }
    },
    created() {
      this.initColumns();
    },
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
